package com.ohuang.fakescreen

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.net.Uri
import android.os.SystemClock
import android.view.*
import android.view.View.OnClickListener
import android.view.View.OnTouchListener
import android.widget.Toast
import androidx.fragment.app.Fragment


fun String?.toBooleanSafe(otherStringBoolean:Boolean):Boolean{
    return when(this){
        "true" -> true
        "false" -> false
        else-> otherStringBoolean
    }
}

inline fun <T> ifElseReturn(
    boolean: Boolean,
    crossinline ifCall: () -> T?,
    crossinline elseCall: () -> T?
): T? {
    if (boolean) {
        return ifCall()
    } else {
        return elseCall()
    }
}
inline fun <T> ifElseReturnNotNull(
    boolean: Boolean,
    crossinline ifCall: () -> T,
    crossinline elseCall: () -> T
): T {
    if (boolean) {
        return ifCall()
    } else {
        return elseCall()
    }
}

fun toColorInt(num: Number): Int {
    return num.toInt()
}

fun Number.toColor(): Int {
    return toInt()
}

fun Context.toastShort(string: String) {
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show()
}

fun Context.toastLong(string: String) {
    Toast.makeText(this, string, Toast.LENGTH_LONG).show()
}

fun  Context.startUrlForBrowser(url: String) {
    var intent = Intent(Intent.ACTION_VIEW)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.addCategory(Intent.CATEGORY_BROWSABLE)
    intent.data = Uri.parse(url)
    startActivity(intent)
}

fun Fragment.toastShort(string: String) {
    Toast.makeText(requireContext(), string, Toast.LENGTH_SHORT).show()
}

fun Fragment.toastLong(string: String) {
    Toast.makeText(requireContext(), string, Toast.LENGTH_LONG).show()
}



fun View.setSafeClickListener(delay: Long = 1000, listener: View.OnClickListener) {
    setOnClickListener(object : OnClickListener {
        var lastClickTime = 0L
        override fun onClick(v: View?) {
            var uptimeMillis = SystemClock.uptimeMillis()
            if (uptimeMillis - lastClickTime > delay) {
                lastClickTime = uptimeMillis
                listener.onClick(v)
            }
        }

    })
}

/**
 * 移动距离要小
 */
fun View.setTouchNoMoveClickListener(onTouchReturn: Boolean = true, listener: OnClickListener){
    setOnTouchListener(object : OnTouchListener {

        var canClick = true
        var overstep = true
        var lastX=0F
        var lastY=0F
        override fun onTouch(v: View?, event: MotionEvent): Boolean {
            val x = event.x
            val y = event.y


            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    overstep = true
                    lastX=x
                    lastY=y
                }
                MotionEvent.ACTION_MOVE -> if (canClick) {
                    if (onTouchReturn) { //onTouchReturn为ture的时候才需要做边界判断
                        v?.let {
                            overstep =
                                (x >= -1) && (y >= -1) && (x <= width + 1) && (y <= height + 1)
                        }
                    }
                    if ((lastX-x)*(lastX-x)+(lastY-y)*(lastY-y)>64){
                        overstep=false
                    }
                    canClick = overstep
                }
                MotionEvent.ACTION_UP -> {
                    if (canClick) {
                        canClick = overstep
                        if (canClick) {
                            listener.onClick(v)
                        }
                    }
                    canClick = true
                }
            }
            return onTouchReturn && canClick
        }
    })
}


/**
 * 若view已设置setonClickListener  onTouchReturn需要设置成false避免事件setonClickListener被拦截
 */
fun View.setTouchClickListener(onTouchReturn: Boolean = true, listener: OnClickListener) {

    setOnTouchListener(object : OnTouchListener {

        var canClick = true
        var overstep = true
        override fun onTouch(v: View?, event: MotionEvent): Boolean {
            val x = event.x
            val y = event.y


            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    overstep = true
                }
                MotionEvent.ACTION_MOVE -> if (canClick) {
                    if (onTouchReturn) { //onTouchReturn为ture的时候才需要做边界判断
                        v?.let {
                            overstep =
                                (x >= -1) && (y >= -1) && (x <= width + 1) && (y <= height + 1)
                        }
                    }
                    canClick = overstep
                }
                MotionEvent.ACTION_UP -> {
                    if (canClick) {
                        canClick = overstep
                        if (canClick) {
                            listener.onClick(v)
                        }
                    }
                    canClick = true
                }
            }
            return onTouchReturn && canClick
        }
    })
}

fun View.setSize(w: Int, h: Int) {
    var lb = layoutParams
    if (lb == null) {
        lb = ViewGroup.MarginLayoutParams(w, h)
    }
    lb.width = w
    lb.height = h
    layoutParams = lb
}

fun View.setWidthSize(w: Int) {
    var lb = layoutParams
    if (lb == null) {
        lb = ViewGroup.MarginLayoutParams(w, -2)
    }
    lb.width = w
    layoutParams = lb
}

fun View.setHeightSize(h: Int) {
    var lb = layoutParams
    if (lb == null) {
        lb = ViewGroup.MarginLayoutParams(-2, h)
    }
    lb.height = h
    layoutParams = lb
}

fun View.setMarginTop(i: Int) {
    var lb = layoutParams
    if (lb is ViewGroup.MarginLayoutParams) {
        lb.topMargin = i
    }
}

fun View.setMarginBottom(i: Int) {
    var lb = layoutParams
    if (lb is ViewGroup.MarginLayoutParams) {
        lb.bottomMargin = i
    }
}

fun View.setMarginLeft(i: Int) {
    var lb = layoutParams
    if (lb is ViewGroup.MarginLayoutParams) {
        lb.leftMargin = i
    }
}

fun View.setMarginRight(i: Int) {
    var lb = layoutParams
    if (lb is ViewGroup.MarginLayoutParams) {
        lb.rightMargin = i
    }
}

fun View.setPaddingLeft(int: Int) {
    setPadding(int, paddingTop, paddingRight, paddingBottom)
}

fun View.setPaddingTop(int: Int) {
    setPadding(paddingLeft, int, paddingRight, paddingBottom)
}

fun View.setPaddingRight(int: Int) {
    setPadding(paddingLeft, paddingTop, int, paddingBottom)
}

fun View.setPaddingBottom(int: Int) {
    setPadding(paddingLeft, paddingTop, paddingRight, int)
}

fun Context.startActivity(activity: Class<out Activity>) {
    var intent = Intent(this, activity)
    if (this is Application) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }
    startActivity(intent)
}

fun Fragment.startActivity(activity: Class<out Activity>) {
    startActivity(Intent(requireContext(), activity))
}



fun Context.createView(layoutId: Int): View {
    return LayoutInflater.from(this).inflate(layoutId, null)
}

fun ViewGroup.createView(layoutId: Int): View {
    return LayoutInflater.from(this.context).inflate(layoutId, this, false)
}



fun Number.dp2px(): Int {
    val scale = Resources.getSystem().displayMetrics.density
    val toDouble = this.toDouble()
    return (toDouble * scale + 0.5f).toInt()
}

fun Number.dp2px(context: Context): Int {
    val scale = context.getResources().getDisplayMetrics().density
    val toDouble = this.toDouble()
    return (toDouble * scale + 0.5f).toInt()
}


fun Number.px2dp(): Int {
    val scale = Resources.getSystem().displayMetrics.density
    val toDouble = this.toDouble()
    return (toDouble / scale + 0.5f).toInt()
}

fun Number.px2dp(context: Context): Int {
    val scale = context.getResources().getDisplayMetrics().density
    val toDouble = this.toDouble()
    return (toDouble / scale + 0.5f).toInt()
}


fun Number.sp2px(): Int {
    val fontScale = Resources.getSystem().displayMetrics.scaledDensity
    val toDouble = this.toDouble()
    return (toDouble * fontScale + 0.5f).toInt()
}

fun Number.sp2px(context: Context): Int {
    val fontScale = context.getResources().getDisplayMetrics().density
    val toDouble = this.toDouble()
    return (toDouble * fontScale + 0.5f).toInt()
}


fun Number.px2sp(): Int {
    val fontScale = Resources.getSystem().displayMetrics.scaledDensity
    val toDouble = this.toDouble()
    return (toDouble / fontScale + 0.5f).toInt()
}

fun Number.px2sp(context: Context): Int {
    val fontScale = context.getResources().getDisplayMetrics().density
    val toDouble = this.toDouble()
    return (toDouble / fontScale + 0.5f).toInt()
}

inline fun tryCatch(block: () -> Unit) {
    try {
        block()
    } catch (_: Exception) {
    }
}

inline fun tryCatch(block: () -> Unit, finally: () -> Unit) {
    try {
        block()
    } catch (_: Exception) {
    } finally {
        finally()
    }
}

inline fun tryCatchPrint(block: () -> Unit) {
    try {
        block()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

inline fun tryCatchPrint(block: () -> Unit, finally: () -> Unit) {
    try {
        block()
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        finally()
    }
}

inline fun tryCatch(block: () -> Unit, error: (Exception) -> Unit) {
    try {
        block()
    } catch (e: Exception) {
        error(e)
    }
}

inline fun tryCatch(block: () -> Unit, error: (Exception) -> Unit, finally: () -> Unit) {
    try {
        block()
    } catch (e: Exception) {
        error(e)
    } finally {
        finally()
    }
}


